package cn.org.eshow.dao.hibernate;

import cn.org.eshow.bean.query.CartQuery;
import cn.org.eshow.common.dao.EnhancedRule;
import cn.org.eshow.common.page.Page;
import cn.org.eshow.dao.CartDao;
import cn.org.eshow.model.Cart;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("cartDao")
public class CartDaoHibernate extends GenericDaoHibernate<Cart, Integer> implements CartDao {


    public CartDaoHibernate() {
        super(Cart.class);
    }

    @Override
    public List<Cart> list(CartQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        return list(rule);
    }

    @Override
    public Page<Cart> search(CartQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        if (query != null) {
            rule.setOffset(query.getOffset());
            rule.setPageSize(query.pagesize);
        }
        return page(rule);
    }

    @Override
    public Long count(CartQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        return count(Cart.class, rule);
    }

    public EnhancedRule setRule(EnhancedRule rule, CartQuery query) {
        if (query != null) {
            if (query.startAddTime != null) {
                rule.add(Restrictions.ge("addTime", query.startAddTime));
            }
            if (query.endAddTime != null) {
                rule.add(Restrictions.le("addTime", query.endAddTime));
            }
            if (StringUtils.isNotEmpty(query.category)) {
                rule.add(Restrictions.eq("category", query.category));
            }
            if (StringUtils.isNotEmpty(query.type)) {
                rule.add(Restrictions.eq("type", query.type));
            }
            if (query.price != null) {
                rule.add(Restrictions.eq("price", query.price));
            }
            if (query.quantity != null) {
                rule.add(Restrictions.eq("quantity", query.quantity));
            }
            if (query.productId != null) {
                rule.add(Restrictions.eq("product.id", query.productId));
            }
            if (query.productItemId != null) {
                rule.add(Restrictions.eq("productItem.id", query.productItemId));
            }
            if (query.userId != null) {
                rule.add(Restrictions.eq("user.id", query.userId));
            }
            if (!StringUtils.isEmpty(query.getOrder())) {
                rule.addOrder(query.getDesc() ? Order.desc(query.getOrder()) : Order.asc(query.getOrder()));
            }
        }
        return rule;
    }

}
